package com.imy.luascript.base.activity;

import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.imy.common.util.ToastUtil;
import com.imy.common.view.recyclerview.adpater.BaseLoadMoreAdapter;
import com.imy.luascript.R;
import com.imy.luascript.utils.NetWorkUtils;
import com.imy.luascript.viewmodel.BaseListViewModel;
import com.jakewharton.rxbinding.view.RxView;

import java.util.List;
import java.util.concurrent.TimeUnit;

import rx.functions.Action1;

/**
 * @ProjectName: frame
 * @Package: com.imy.frame.base.activity
 * @ClassName: BaseListViewAdapter
 * @Description: 描述
 * @Author: Imy
 * @CreateDate: 2020/11/2 10:06
 */
public abstract class BaseListActivity<V extends BaseListViewModel, A extends BaseLoadMoreAdapter> extends BaseViewActivity<V> {

    protected SwipeRefreshLayout swipeRefreshLayout;
    protected RecyclerView recyclerView;
    private A adapter;
    protected boolean isLoading;//是否正在加载中（即翻页，上拉加载更多）
    protected boolean isRefresh;//是否在刷新中（下拉刷新）
    protected boolean loadNextPageDataIsError;//是否翻页异常（即翻页，上拉加载更多）

    @Override
    protected void initView() {

        swipeRefreshLayout = findViewById(R.id.common_swipe_refresh);
        recyclerView = findViewById(R.id.common_recycler_view);
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorPrimary),
                    getResources().getColor(R.color.colorPrimary));
        }
        setLayoutManager();
        if (recyclerView.getItemAnimator() != null) {
            SimpleItemAnimator simpleItemAnimator = (SimpleItemAnimator) recyclerView.getItemAnimator();
            simpleItemAnimator.setSupportsChangeAnimations(false);
        }
        adapter = createAdapter();
        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        setRecyclerViewListener();
    }


    private void setRecyclerViewListener() {
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    if (NetWorkUtils.isConnected(self)) {
                        if (!isRefresh && !isLoading) {
                            isRefresh = true;
                            isLoading = true;
                            mViewModel.refreshData();
                        } else {
                            swipeRefreshLayout.setRefreshing(false);
                        }
                    } else {//如果网络异常，直接提示
                        loadCompleted();
                        ToastUtil.toast(getApplicationContext(),getString(R.string.tips_network_error2));
                    }
                }
            });
        }
        loadMoreListener();
    }

    private void loadMoreListener() {
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                //当前RecyclerView显示出来的最后一个的item的position
                int lastPosition = -1;
                switch (newState) {
                    case RecyclerView.SCROLL_STATE_IDLE://当屏幕停止滚动
                        if (adapter.isHaveStatesView()) {//只有有底部加载，才需要监听是否滑到底部需要执行相应的动作
                            RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                            if (layoutManager instanceof GridLayoutManager) {
                                //通过LayoutManager找到当前显示的最后的item的position
                                lastPosition = ((GridLayoutManager) layoutManager).findLastVisibleItemPosition();
                            } else if (layoutManager instanceof StaggeredGridLayoutManager) {
                                int into[] = new int[((StaggeredGridLayoutManager) layoutManager).getSpanCount()];
                                ((StaggeredGridLayoutManager) layoutManager).findLastVisibleItemPositions(into);
                                lastPosition = findMax(into);
                            } else if (layoutManager instanceof LinearLayoutManager) {
                                lastPosition = ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition();
                            }
                            //时判断界面显示的最后item的position是否等于itemCount总数-1也就是最后一个item的position
                            //如果相等则说明已经滑动到最后了
                            if (lastPosition == layoutManager.getItemCount() - 1) {
                                if (mViewModel.hasNextPage()) {//还有下一页
                                    if (!loadNextPageDataIsError && !isLoading) {//只有翻页不出问题，且没有在加载中，才能继续翻页
                                        isLoading = true;
                                        adapter.showLoadMore();
                                        mViewModel.loadNextPageData();
                                    }
                                }
                            }
                        }

                        break;
                    case RecyclerView.SCROLL_STATE_DRAGGING:

                        break;
                    case RecyclerView.SCROLL_STATE_SETTLING:

                        break;
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

            }
        });
    }

    protected <T> void loadList(List<T> list) {
        if (mViewModel.getPage()==1){
            adapter.getItems().clear();
        }
        adapter.getItems().addAll(list);
        adapter.notifyDataSetChanged();
        loadCompleted();
    }

    private void showAdapterLoadError() {
        adapter.showLoadError(new BaseLoadMoreAdapter.CallBack() {
            @Override
            public void onErrorViewClick(View view) {
                //添加防连续点击，1500毫秒之后才能继续点击
                RxView.clicks(view)
                        .throttleFirst(1500, TimeUnit.MILLISECONDS)
                        .subscribe(new Action1<Void>() {
                            @Override
                            public void call(Void aVoid) {
                                if (!NetWorkUtils.isConnected(self)) {
                                    ToastUtil.toast(getApplicationContext(),getResources().getString(R.string.tips_network_error2));
                                } else if (!isLoading) {
                                    isLoading = true;
                                    loadNextPageDataIsError = false;
                                    adapter.showLoadMore();
                                    mViewModel.loadData();
                                }
                            }
                        });
            }
        });
    }

    private void loadCompleted() {
        isLoading = false;
        isRefresh = false;
        //因为列表页有可能不需要下拉刷新
        if (swipeRefreshLayout != null) {
            if (swipeRefreshLayout.isRefreshing()) {
                swipeRefreshLayout.setRefreshing(false);
            }
        }
    }

    /**
     * 默认是底部没有加载更多视图，如果不需要底部加载更多，
     * 在实现类重写的initViewAndData()，调用mAdapter.setHaveStatesView(false)
     */
    protected void setHaveStatesView() {

        adapter.setHaveStatesView(true);
    }

    /**
     * 设置RecyclerView分割线,如果不需要设置分割线，无需实现
     * demp:
     * mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mActivity)
     * .color(mActivity.getResources().getColor(R.color.transparence))//设置分割线颜色
     * .size(mActivity.getResources().getDimensionPixelSize(R.dimen.anli_wall_item_interval_height))//设置分割线高度
     * .visibilityProvider(mAdapter)//如果需要控制某个item位置是否显示分割线，如果写这个方法，adapter需要实现implements
     * FlexibleDividerDecoration.VisibilityProvider，如果都显示分割线就不需要调用.visibilityProvider(mAdapter)
     * .build());
     */
    protected void addItemDecoration() {
    }

    private void setLayoutManager() {
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
    }

    protected abstract A createAdapter();

    //找到数组中的最大值
    private int findMax(int[] lastPositions) {
        int max = lastPositions[0];
        for (int value : lastPositions) {
            if (value > max) {
                max = value;
            }
        }
        return max;
    }

}